package context;

import lombok.SneakyThrows;
import model.ExecuteMethod;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @className: SoiNodeHolder
 * @author: ocxz1
 * @date: 2025/3/12 上午11:29
 * @Version: 1.0
 * @description: soi 节点holder
 */
public class SoiMethodHolder implements Holder<String, ExecuteMethod>{

    private static final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private static final Lock readLock = rwLock.readLock();
    private static final Lock writeLock = rwLock.writeLock();

    private static final Map<String, ExecuteMethod> executeMethodHolder = new ConcurrentHashMap<>();

    private static final Map<String, Class<?>> classHolder = new ConcurrentHashMap<>();

    public static ExecuteMethod getExecuteMethod(String key) {
        return executeMethodHolder.get(key);
    }

    @Override
    public void push(String key, ExecuteMethod executeMethod) {
        executeMethodHolder.put(key, executeMethod);
    }

    @Override
    public ExecuteMethod get(String key) {
        return executeMethodHolder.get(key);
    }

    public static Class<?> getClass(String key) {
        Class<?> aClass;
        readLock.lock();
        try {
            aClass = classHolder.get(key);
        } finally {
            readLock.unlock();
        }
        return Objects.requireNonNullElseGet(aClass, () -> putClass(key));
    }

    @SneakyThrows
    public static Class<?> putClass(String key) {
        writeLock.lock();
        try {
            Class<?> aClass = Class.forName(key);
            classHolder.putIfAbsent(key, aClass);
            return aClass;
        } finally {
            writeLock.unlock();
        }
    }
}
